package 左哥算法.ch06二叉树;

import java.util.LinkedList;
import java.util.Queue;

public class TreeNode2 {
    int val;
    TreeNode2 left;
    TreeNode2 right;
    TreeNode2 parent;
    TreeNode2() {}
    TreeNode2(Integer val) { this.val = val; }

    TreeNode2(Integer val,TreeNode2 parent) {
        this.val = val;
        this.parent=parent;
    }

    public static TreeNode2 newLevelTree(Integer[] arr){
        if (arr.length==0||arr[0]==null){
            return null;
        }
        TreeNode2 root=new TreeNode2(arr[0]);
        Queue<TreeNode2> queue=new LinkedList<>();
        int left=-1,right=-1;
        queue.add(root);
        root.parent=null;
        for (int index = 0; index < arr.length; index++) {
            TreeNode2 node = queue.poll();
            if (node!=null){
                left=index*2+1;
                right=index*2+2;
                node.left=left<arr.length&&arr[left]!=null?     //左侧存在且不为空
                        new TreeNode2(arr[left],node):null;
                node.right=right<arr.length&&arr[right]!=null?     //左侧存在且不为空
                        new TreeNode2(arr[right],node):null;
                queue.add(node.left);
                queue.add(node.right);
            }
        }
        return root;
    }
    public String toString() {
        return val+" ";
    }
}
